<template>
  <div
    class="face"
    element-loading-text="识别中..."
    v-loading="loading"
    customClass="el-icon-loading"
  >
    <h1 class="title">{{ tack }}</h1>
    <div class="testTracking">
      <video
      ref="video"
        id="video"
        preload
        autoplay
        loop
        muted
        playsinline
        height="1024px"
        width="768px"
      ></video>
      <canvas id="canvas" height="500px" width="600px"></canvas>
      <div class="djs" v-show="isNum">
        {{ NumKs }}
      </div>
    </div>
    <div style="text-align: center;font-size: 22px;margin-top: 30px;" v-if="Number(outTime)">
      请在规定时间内完成人脸验证，剩余时间：<span style="font-size: 30px;color: #f00;">{{ outTime }}</span> 秒
    </div>
    <!-- <div class="backgroundblack" v-show="backgroundblack"></div> -->
  </div>
</template>

<script>
// require('build/tracking-min.js')
// require('build/data/face-min.js')
// require('build/data/mouth-min.js')
// require('examples/assets/stats.min.js')
// import axios from 'axios'
// import qs from 'qs'
import "./build/tracking.js";
import "./build/data/face-min.js";
import "./build/data/mouth-min.js";
import "./build/data/eye-min.js";
import { dataURLtoFile } from "@/utils/64batatoFile.js";
import { faceInit, faceupload, facecompare } from "@/api/admin.js";
import { mapGetters } from "vuex";
import {
  getapplyid,
  setisfacetime,
  delisfacetime,
  setisfacetimemkface,
  delisfacetimemkface,
  setisfacetimezxface,
  setisfacetimekjface,
  delisfacetimezxface,
  delisfacetimekjface,
  setisfacetimezsface,
  getGZ
} from "@/utils/auth.js";
export default {
  computed: {
    ...mapGetters(["userinfor",'initObj']),
  },
  props: {
    comments: {
      type: Boolean,
      default: false,
    },
    show: {
      type: Boolean,
      default: false,
    },
    type:{
      type:String,
      default:'',
    }
  },
  data() {
    return {
      video: true,
      backgroundblack: true,
      isFace: false,
      tack: "未检测出人脸",
      NumKs: 2,
      objTime: Object,
      isNum: false,
      imgURl: "",
      Photo: true,
      isPhoto: false,
      loading: false,
      src: "",
      applyid: getapplyid(),
      hasFace: this.$route&&this.$route.query&&this.$route.query.hasFace ? this.$route.query.hasFace : "",
      desFace: this.$route&&this.$route.query&&this.$route.query.desFace ? this.$route.query.desFace : "",
      tracker: Object,
      cishu: 0, //验证次数
      title: "此功能需要人脸验证后才能使用,是否开始验证",
      isShowIos: navigator.userAgent.match(/(iPhone|iPod|ios|iOS|iPad)/i),
      http:
        process.env.NODE_ENV === "development"
          ? process.env.VUE_APP_BASE_API
          : window.location.href.slice(
              0,
              window.location.href.indexOf("/user")
            ),
      outTime:0,//faceOutTime
      outTimeObj:null,
      facenum:3,  
    };
  },
  watch: {
  },
  methods: {
    openCameraA() {
      var _this = this;
      this.NumKs = 3;
      this.isNum = false;
      // console.log(222,this.tracker);
      this.tracker = new tracking.ObjectTracker("face");
      this.trackerTask = tracking.track("#video", this.tracker, {
        camera: true,
      });
      this.tracker.setInitialScale(4);
      this.tracker.setStepSize(2);
      this.tracker.setEdgesDensity(0.1);
      
      this.tracker.on("track", this.faceFunction);
      // setTimeout(()=>{
      //   // console.log(document.getElementById('video').srcObject);
      //   // this.tracker.stop()
        
      // },5000)
    },
    commitFace(event, canvas, video, context) {
      this.tack = "识别中...";
      // this.loading=true
      // this.Photo = false;
      document.getElementById("video").pause()
      this.isNum = false;
      // this.trackerTask.stop('track')
      this.tracker.removeListener("track", this.faceFunction)
      clearInterval(this.objTime);
      event.data.forEach((rect) => {
        context.font = "11px Helvetica";
        context.strokeStyle = "#a64ceb";
        // context.strokeRect(-100, -100, canvas.width,canvas.height-200);
        // context.fillRect(-100,-100,rect.width,rect.height-200);
        // context.translate((canvas.width - canvas.width * -1) / 2, 0);
        context.scale(1,1)
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        this.imgURl = canvas.toDataURL("image/png", 1);
        this.uploadImg(dataURLtoFile(this.imgURl, "1"));
        this.$lrz(this.imgURl, { quality: 0.8 }).then((res) => {
          // this.src = res.base64
        });
      });
    },
    //人脸侦测功能
    faceFunction(event) {
      var _this = this;
      var video = document.getElementById("video");
      var canvas = document.getElementById("canvas");
      var context = canvas.getContext("2d");
      context.beginPath();
      context.stroke();
      if (event.data.length == 0 && !this.isPhoto) {
        this.tack = "未检测出人脸,请开启设备摄像头并正确验证学员人脸";
        this.NumKs = 3;
        this.isNum = false;
      } else {
        if (!this.isPhoto) {
          this.isPhoto = true;
          this.isNum = true;
          this.tack = "检测到人脸信息，请将人像移动至框内并保持2-3秒不动";
          clearInterval(this.objTime);
          this.objTime = setInterval(() => {
            if (this.NumKs == 0) {
              this.commitFace(event, canvas, video, context);
            }
            this.NumKs--;
          }, 1000);
        }
      }
    },
    //上传至服务器
    uploadImg(file) {
      let formData = new FormData();
      formData.append("image_file", file);
      formData.append("image_field", "face");
      faceupload(formData).then((res) => {
        if (res.code == 200) {
          if (this.desFace) {
            this.bottomPhoto(res.data.image_src);
          } else {
            this.cpFace(res.data.image_src);
          }
        } else {
          this.$message.error("请稍后再试！");
        }
      });
    },
    // 底片存入
    bottomPhoto(src) {
      let obj = {
        applyid: this.applyid,
        face: src,
      };
      faceInit(obj).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.trackerTask.stop("track");
          this.$message.success("照片存入成功");
          this.$router.go(-1);
        } else {
          this.$message.error(res.msg);
          document.getElementById("video").play()
          this.isPhoto = false;
        }
      });
    },
    //人脸对比
    cpFace(src) {
      let type = this.$route.query.type || this.type
      let obj = {};
      if (this.hasFace == "zsface") {
        obj = {
          applyid: this.applyid,
          face: src,
          type: "exam",
          verifyFace:JSON.parse(this.initObj.is_face)[getGZ()].zsface=='公安部识别'?1:0
        };
      } else {
        obj = {
          applyid: this.applyid,
          face: src,
          verifyFace:type&&JSON.parse(this.initObj.is_face)[getGZ()][type]=='公安部识别'?1:0
        };
      }
      this.loading = true;
      facecompare(obj).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          clearInterval(this.outTimeObj)
          // this.trackerTask.stop("track");
          this.$message.success("人脸验证成功");
          if (this.hasFace == "openFaces") {
            setisfacetime(obj);
            setisfacetimemkface(obj);
            setisfacetimezxface(obj);
            setisfacetimekjface(obj);
          }
          if (this.hasFace == "mkface") {
            setisfacetimemkface(obj);
            delisfacetimezxface();
            delisfacetimekjface();
            delisfacetime();
          }
          if (this.hasFace == "zxface") {
            setisfacetimezxface(obj);
            delisfacetimemkface();
            delisfacetimekjface();
            delisfacetime();
          }
          if (this.hasFace == "kjface") {
            setisfacetimekjface(obj);
            delisfacetimemkface();
            delisfacetimezxface();
            delisfacetime();
          }
          if (this.hasFace == "zsface") {
            setisfacetimezsface(obj);
          }
          if (this.comments) {
            this.$emit("update:show", false);
            this.src = "";
          } else {
            this.$router.go(-1);
          }
        } else {
          this.tack = "未检测出人脸,请开启设备摄像头并正确验证学员人脸";
          document.getElementById("video").play()
          this.isPhoto = false;
          this.NumKs = 3;
          this.isNum = false;
          this.tracker.on("track", this.faceFunction);
          this.facenum--
          if(this.facenum==0){
            this.tracker.removeListener("track", this.faceFunction);
            this.src = null;
            this.$router.push("/");
            return this.$message.error("人脸验证失败超过三次,自动退出验证");
          }
          if (this.comments) {
            // this.$router.push("/");
          } else {
            if (this.http.indexOf("putai") == -1) {
              this.$message.error("人脸验证失败,请重新验证");
            }else{
              this.tracker.removeListener("track", this.faceFunction);
              this.src = null;
              this.$router.push("/");
            }
            
           
            // this.$router.push("/");
            // this.faceFunction()
          }
          
          
        }
      });
    },
    open() {
      // var video = document.getElementById('video');
      // var canvas = document.getElementById('canvas');
      // var context = canvas.getContext('2d');
      // setisfacetimekjface({applyid: this.applyid,
      //     face: '',});
      this.openCameraA();
      // navigator.mediaDevices.getUserMedia({video: true,audio:false}).then(stream=>{
      //   console.log(stream,'1211151511')
      //   this.$nextTick(() => {
      //     video.srcObject = stream;//that.video是video标签节点，请自行获取节点，updated周期里可以拿到！
      //     video.play();
      //   });
      // })
    },
    //照片旋转
    removePicExif(file) {
      return new Promise((reslove) => {
        if (file) {
          let reader = new FileReader();
          let image = new Image();
          reader.onload = function (ev) {
            image.src = ev.target.result;
            image.onload = function () {
              const ctxWidth = this.width;
              const ctxHeight = this.height;
              const canvas = document.createElement("canvas");
              const ctx = canvas.getContext("2d");
              canvas.width = ctxWidth;
              canvas.height = ctxHeight;
              ctx.drawImage(this, 0, 0, ctxWidth, ctxHeight);
              canvas.toBlob((blob) => {
                const newFile = new File([blob], file.name, {
                  type: "image/jpeg",
                  lastModified: Date.now(),
                });
                reslove(newFile);
              });
            };
          };
          reader.readAsDataURL(file);
        }
      });
    },
    //打开相机
    async openCamera(data) {
      if (data.target.files.length == 0) {
        return;
      }
      this.$lrz(await this.removePicExif(data.target.files[0]), {
        quality: 0.7,
      }).then((res) => {
        this.src = res.base64;
        this.uploadImg(dataURLtoFile(res.base64, res.origin.name));
      });
    },
  },
  mounted() {
    if(!this.desFace){
      let facetimeout = JSON.parse(this.initObj.setting).faceOutTime
      this.outTime =facetimeout? facetimeout * 60:0
      const that = this
      if(this.outTime&&this.outTime!=0){
        this.outTimeObj=setInterval(() => {
          this.outTime--
          if(this.outTime==0){
            clearInterval(this.outTimeObj)
            // document.getElementById('video').srcObject = null
            // this.tracker.removeListener("track")
            // this.video.srcObject = null
            this.$message.warning({
              message:'未在规定时间内完成验证，将自动返回',
              duration:4000,
              onClose(){
                that.$router.go(-1)
              }
            })
          }
        }, 1000);
      }
    }
    this.open();
  },
  beforeDestroy(){
    // console.log(document.getElementById('video'),this.$refs.video);
    if(this.$refs.video.srcObject){
      this.$refs.video.srcObject.getTracks().forEach(function(track) {
        if (track.readyState == 'live') {
          console.log(123);
          track.stop();
        }
      });
      this.$refs.video.srcObject = null
    }
  },
  destroyed() {
    // this.video.srcObject = null
    // this.tracker.removeListener("track")
    this.tracker.removeListener("track", this.faceFunction)
    
    // if(document.getElementById('video').srcObject){
    //   document.getElementById('video').srcObject.getTracks().forEach(function(track) {
    //     if (track.readyState == 'live') {
    //       track.stop();
    //     }
    //   });
    //   document.getElementById('video').srcObject = null
    // }
    // this.tracker = new Object()
    // 停止侦测
    // this.trackerTask.stop('track')
    // 关闭摄像头
    // this.trackerTask.closeCamera()
  },
  created() {
    if (this.desFace) {
      this.title = "初次使用人脸识别，请录入头像信息";
    } else {
      this.title = "此功能需要人脸验证后才能使用，是否开始验证";
    }
    if (this.comments) {
      this.title = "此功能需要人脸验证后才能使用，是否开始验证";
    }
  },
};
</script>

<style lang="scss" scoped>
.face {
  height: 100%;
  width: 100%;
  position: fixed;
  background-size: 100% 100%;
  z-index: 10;
}
.result {
  position: absolute;
  font-size: 0.05rem;
  bottom: 3%;
  text-align: center;
  width: 100%;
  color: #fff;
}
.opacity {
  opacity: 0;
}
.testTracking {
  // >* {
  //   position: absolute;
  //   left: 0;
  //   right: 0;
  //   margin: auto;
  // }
  video {
    // position: absolute;
    width: 580px;
    height: 750px;
    // top:10.5%;
    // left: 0;
    // right: 0;
    margin-left: calc(-290px + 10rem);
    margin-top: -100px;
    padding: 0;
    // border-radius: 50%;
    object-fit: cover;
    transform: rotateY(180deg);
    // z-index: 10;
  }
  // .bgBax{
  //   position: absolute;
  //   width:20rem;
  //   height:20rem;
  //   top:10.5%;
  //   left: 0;
  //   right: 0;
  //   margin: auto;
  //   padding:0;
  //   border-radius: 50%;
  //   z-index: 11;
  //   background: #fff;
  // }
  // img{
  //   position: absolute;
  //   width:20.2rem;
  //   height: 20.2rem;
  //   top:10.5%;
  //   left: 0;
  //   right: 0;
  //   margin: auto;
  //   padding:0;
  //   border-radius: 50%;
  // }
  canvas {
    // position: absolute;
    width: 750px;
    height: 520px;
    // top:60px;
    // left: 0;
    // right: 0;
    // margin: auto;
    margin-left: calc(-290px + 10rem);
    margin-top: -40px;
    padding: 0;
    object-fit: cover;
    transform: rotateY(180deg);
    /* border-radius: 50%; */
    z-index: 0;
  }
  .buttonDiv {
    bottom: 10px;
  }
}
.testTracking {
  ::v-deep {
    #stats {
      display: none;
    }
  }
}
.testTracking {
  ::v-deep {
    #fps {
      display: none;
    }
  }
}
.testTracking {
  z-index: 10;
  width: 20rem;
  height: 20rem;
  border-radius: 50%;
  overflow: hidden;
  margin: auto;
  margin-top: 100px;
  ::v-deep {
    element.style {
      // padding: 0px 0px 3px 3px;
      text-align: left;
      background-color: rgb(0, 34, 0);
      display: none;
    }
  }
}
.log {
  display: block;
  height: 1.2rem;
  width: 3.8rem;
  position: absolute;
  left: 2%;
  top: 4.5%;
}
h1 {
  font-size: 1.8rem;
  font-family: Microsoft YaHei;
  font-weight: 400;
  // background:linear-gradient(0deg,rgba(255,255,255,1) 0%, rgba(219,219,219,1) 24.1943359375%, rgba(255,255,255,1) 46.4111328125%, rgba(227,227,226,1) 65.673828125%, rgba(255,255,255,1) 88.1591796875%);
  -webkit-background-clip: text;
  // -webkit-text-fill-color:transparent;
  display: block;
  width: 100%;
  text-align: center;
  position: absolute;
  top: 2.39rem;
  color: #000;
  z-index: 10;
  // margin-top:10%;
}
.prompt {
  font-size: 0.7rem;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
  display: block;
  width: 100%;
  text-align: center;
  background: linear-gradient(
    0deg,
    rgba(255, 255, 255, 1) 0%,
    rgba(219, 219, 219, 1) 24.1943359375%,
    rgba(255, 255, 255, 1) 46.4111328125%,
    rgba(227, 227, 226, 1) 65.673828125%,
    rgba(255, 255, 255, 1) 88.1591796875%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  position: absolute;
  top: 4.18rem;
}
.inputbox {
  width: 9.4rem;
  height: 5.5rem;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  background: rgba(242, 242, 242, 1);
  border-radius: 0.2rem;
  z-index: 100;
}
.inputbox p {
  width: 100%;
  height: 15%;
  position: absolute;
  font-size: 0.6rem;
  left: 0;
  top: 0.6rem;
  bottom: 0;
  right: 0;
  margin: 0 auto;
  text-align: center;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(51, 51, 51, 1);
}
.inputbox .errorp {
  position: absolute;
  left: 0;
  top: 30%;
  bottom: 0;
  right: 0;
  margin: 0 auto;
}
.inputbox input {
  width: 85%;
  height: 1.2rem;
  display: block;
  position: absolute;
  left: 0;
  top: 2rem;
  bottom: 0;
  right: 0;
  margin: 0 auto;
  background: rgba(229, 229, 229, 1);
  border-radius: 0.62rem;
  border: none;
  font-size: 0.6rem;
  line-height: 1.2rem;
  text-align: center;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(95, 103, 115, 1);
  // background: red;
}
.inputbox .inputbutton {
  height: 21%;
  width: 100%;
  border-top: 1px solid rgba(229, 229, 229, 1);
  position: absolute;
  bottom: 0;
  display: flex;
  justify-content: space-between;
}
.inputbox .clearinput {
  font-size: 0.24rem;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(150, 158, 171, 1);
  width: 0.5rem;
  height: 0.5rem;
  line-height: 0.5rem;
  text-align: center;
  background: rgba(255, 255, 255, 1);
  border-radius: 50%;
  position: absolute;
  left: 84%;
  top: 2.3rem;
  bottom: 0;
  // right: 0;
  margin: 0 auto;
}
.inputbox .inputbutton button {
  outline: none;
  height: 100%;
  width: 100%;
  border: none;
  background: rgba(242, 242, 242, 1);
  border-right: 1px solid rgba(229, 229, 229, 1);
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(49, 51, 55, 1);
  font-size: 0.5rem;
  border-radius: 0 0 0.2rem 0.2rem;
}
.inputbox .inputbutton .cancel {
  color: rgba(150, 158, 171, 1);
}
.inputbox .inputbutton .errorinputbutton {
  width: 100%;
  border: none;
}
.backgroundblack {
  width: 100%;
  height: 100%;
  position: fixed;
  background: #fff;
  z-index: 5;
  // opacity:0.5;
}
#result[data-v-15b437a0] {
  // opacity: 0;
}
.djs {
  color: #fff;
  position: absolute;
  width: 20.2rem;
  height: 20.2rem;
  top: 10.5%;
  left: 0;
  right: 0;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  // opacity: 0;
  font-size: 10rem;
  z-index: 10;
}

.bjbox {
  height: 100vh;
  width: 100vw;
  background: rgba($color: #000000, $alpha: 0.3);
  display: flex;
  justify-content: center;
}
.tsBox {
  padding: 1.2rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  width: 80vw;
  margin-top: 20%;
  border-radius: 12px;
  &::before {
    content: "人脸识别";
    font-size: 1.5rem;
  }
}
.camera {
  opacity: 0;
  width: 100%;
  height: 1.87rem;
  position: absolute;
  z-index: 2;
  // display: none;
}
.cameraBox {
  position: relative;
  display: inline-block;
  width: 5.62rem;
  margin-left: 0.75rem;
  .info {
    position: absolute;
    left: 0;
    z-index: 1;
  }
}
.van-button {
  height: 2rem;
  width: 6rem;
  // width:100%;
}
.van-button--normal {
  padding: 0 !important;
}
img {
  width: 9.37rem;
  height: 9.37rem;
  // transform:rotate(-90deg);
}
</style>
